#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "config.h"
#include <QWidget>
#include <QTcpServer>
#include <QNetworkInterface>
#include <QDebug>
#include <QMessageBox>
#include <QTcpSocket>


MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    this->setWindowTitle("局域网文件传输管理工具(服务端)");
    this->setFixedSize(WINDOW_WIDTH,WINDOW_HEIGHT);
    this->setWindowIcon(QIcon(WINDOWS_ICO_PATH));
    pic.load(BACK_PATH);

    //数据初始化
    Initialize();

}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::Initialize()
{
    TCPServer = new QTcpServer(this);
    TCPSocket = new QTcpSocket(this);
//    TcpSocket = new QTcpSocket(this);
    QHostInfo info = QHostInfo::fromName(QHostInfo::localHostName()); //从主机名（我的为"Zxeao"）获取IP地址
//    qDebug()<<"!!!";
//    QString ip= info.addresses().at(1).toString();      //要把info转换为QString才能把它放到文本框中
    QString ip= QNetworkInterface().allAddresses().at(1).toString();
    qDebug() <<"IP Address: "<<info.addresses();
//    ui->IPText->setText(QNetworkInterface().allAddresses().at(1).toString());
    ui->IPText->setText(ip);
    ui->state->setText("未有客户端连接");
    this->isconnection=false;

    ui->LableIP->setVisible(false);
    ui->LablePort->setVisible(false);
    ui->lineEditIP->setVisible(false);
    ui->lineEditPort->setVisible(false);

}

void MainWindow::paintEvent(QPaintEvent *event)
{
    QPainter painter(this);
    painter.drawPixmap(0,0,pic);
}

void MainWindow::ServerNewConnection()

{
    TCPSocket = TCPServer->nextPendingConnection();  //客户端的连接，获取客户端描述符

    connect(TCPSocket,SIGNAL(readyRead()),this,SLOT(RecvMessage())); //连接客户端的套接字的有新消息信号到接收消息的槽

    connect(TCPSocket,SIGNAL(disconnected()),this,SLOT(DisConnect())); //连接客户端的套接字取消连接信号到取消连接槽

    ui->state->setText("有客户端连接");

    QMessageBox::information(this, "QT网络通信", "有客户端连接！");

//    qDebug() << "Address:" << TCPSocket->peerAddress ();
//    qDebug() << "Port:" << TCPSocket->peerPort  ();

    this->isconnection=true;

    QString IP = TCPSocket->peerAddress().toString();//获取客户端ip
    quint16 TPort = TCPSocket->peerPort();            //获取客户端端口
    QString Port = QString::number(TPort);

    ui->LableIP->setVisible(true);
    ui->LablePort->setVisible(true);

    ui->lineEditIP->setVisible(true);
    ui->lineEditPort->setVisible(true);

    ui->lineEditIP->setText(IP);
    ui->lineEditPort->setText(Port);

    ui->slot_disconnect->setEnabled(true);

//    TCPSocket->close();   //关闭服务器不再监听，直接进入数据收发
}

void MainWindow::on_Start_clicked()
{
    if(!TCPServer->listen(QHostAddress::Any, 6666))
    {
         QMessageBox::information(this, "QT网络通信", "服务器端监听失败！");
         return;
    }
    else
    {
        ui->LabelState->setText("监听已开启！");
        QMessageBox::information(this, "QT网络通信", "服务器端监听启动！");
        ui->Start->setEnabled(false);
        connect(TCPServer, SIGNAL(newConnection()), this, SLOT(ServerNewConnection()));
        return;
    }
}

void MainWindow::on_Exit_clicked()
{
    QMessageBox::information(this, "QT网络通信", "服务器端监听结束！");

    this->close();
}

void MainWindow::RecvMessage()
{

    if(TCPSocket != nullptr) //与客户端连接的socket，不是nullptr，则说明有客户端存在
    {
        QMessageBox::information(this, "QT网络通信", "有新消息！");
        QByteArray array = TCPSocket->readAll();    //接收消息
        QHostAddress clientaddr = TCPSocket->peerAddress(); //获得IP
        int port = TCPSocket->peerPort();   //获得端口号

        QDateTime datetime = QDateTime::currentDateTime();

        QString sendMessage = tr("recv from :") + clientaddr.toString() + tr(" : ") \
                                + QString::number(port) + tr("   \n") + datetime.toString("yyyy-M-dd hh:mm:ss") + tr("\n");
        sendMessage += array;

        ui->textBrowser->append(sendMessage);   //将接收到的内容加入到listwidget
    }
}

void MainWindow::DisConnect()
{
    if(TCPSocket != nullptr && this->isconnection)
    {
        this->isconnection=false;
        ui->textBrowser->append("连接断开!");
        ui->slot_disconnect->setEnabled(false);
        TCPSocket->disconnectFromHost();
        QMessageBox::information(this, "QT网络通信", "断开与客户端的连接！");
        ui->state->setText("未有客户端连接");

//        TCPSocket->close(); //关闭客户端
//        TCPSocket->deleteLater();//deletelater的原理是 QObject::deleteLater()并没有将对象立即销毁，而是向主消息循环发送了一个event，下一次主消息循环收到这个event之后才会销毁对象。
    }
}

void MainWindow::solt_SendMessage()
{
    if(this->isconnection)
    {
        QString sendMessage = ui->lineEdit->text(); //从单行文本框获得要发送消息
        if(!sendMessage.isEmpty())
        {
            //发送消息到服务器
            this->TCPSocket->write(sendMessage.toLatin1());
//            this->TCPSocket->waitForBytesWritten();
            //本地显示发送的消息
            QString localDispalyMessage = tr("send to server: ") + sendMessage \
                                            + QDateTime::currentDateTime().toString(" yyyy-M-dd hh:mm:ss") + tr("\n");
            ui->textBrowser->append(localDispalyMessage);
        }
        else
            QMessageBox::warning(this,"错误","消息不能为空!",QMessageBox::Ok);
    }
    else
        QMessageBox::warning(this,"错误","未连接到服务器!",QMessageBox::Ok);

    ui->lineEdit->clear();
}

void MainWindow::on_pushButton_Sent_clicked()
{
    solt_SendMessage();
}

void MainWindow::on_pushButton_clicked()
{
    ui->textBrowser->clear();
}

void MainWindow::on_slot_disconnect_clicked()
{

    this->DisConnect();
}
